﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Peradigm.Framework.Configuration;
using Peradigm.Framework.Domain.Security;

using Liberty.Persistence.GrantManagement;
using Liberty.Domain.CaseManagement;
using Liberty.Domain.GrantManagement;

namespace Liberty.Application.Security
{

    [Serializable]
    public class DisperseGrantPrivilege : Privilege
    {
        #region Constants
        public const string
            KEY_GRANT = "Grant",
            KEY_USER = "CurrentUser",
            PRIVILEGE_DISPERSE_GRANT = "Grant.Disperse";

        private const string CXN_STRING_KEY = "ConnectionString";
        #endregion

        #region Event Handlers
        #endregion

        #region Methods
        /// <summary>
        /// 
        /// </summary>
        /// <param name="action">
        /// </param>
        /// <param name="context">
        /// </param>
        /// <returns>
        /// </returns>
        public override bool Equals( Actions action, object context )
        {
            bool areEquivalent = false;
            Dictionary<string, object> contextItems = context as Dictionary<string, object>;
            if( contextItems != null )
            {
                Grant grant = contextItems[KEY_GRANT] as Grant;
                User currentUser = contextItems[KEY_USER] as User;
                if ( contextItems.ContainsKey( PRIVILEGE_DISPERSE_GRANT ) )
                {
                    areEquivalent = this.CanDisperse( grant, currentUser );
                }
            }

            return areEquivalent;
        }
        #endregion

        #region Properties
        #endregion

        #region Private Methods
        private bool CanDisperse( Grant grant, User currentUser )
        {
            GrantBroker grantBroker = new GrantBroker( this.ConnectionString );
            GrantState awaitingDispersal = grantBroker.GrantStateWith( (long)GrantStateOID.AwaitingDispersal );
            bool canDisperse;
            GrantState stateOfGrant = grant.Status;

            canDisperse = ( 
                                stateOfGrant.Equals( awaitingDispersal ) 
                                && currentUser.IsInRole( LibertyApplication.LIBERTY_FINANCIAL_APPROVER ) 
                          );
            return canDisperse;
        }
        #endregion

        #region Private Properties
        private string ConnectionString
        {
            get
            {
                return ApplicationConfiguration.Settings[CXN_STRING_KEY];
            }
        }
        #endregion

        #region Construction and Finalization
        public DisperseGrantPrivilege( Actions action, object context )
            : base( action, context )
        {
        }
        #endregion

        #region Data Elements
        #endregion
        
    }
}
